<template>
  <div class="appointment-manage">
    <div class="page-header">
      <i class="el-icon-time"></i>
      <span>预约管理</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入客户姓名/手机号进行搜索"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleSearch">查询</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="!selectedRows.length">删除</el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column label="充电桩编号" min-width="140" align="center">
        <template slot-scope="scope">
          {{ scope.row.chargerNumber }} ({{ scope.row.chargerName }})
        </template>
      </el-table-column>
      <el-table-column label="预约时长" min-width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.reservationDuration }}分钟
        </template>
      </el-table-column>
      <el-table-column label="预约开始时间" min-width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.reservationStartTime }}
        </template>
      </el-table-column>
      <el-table-column prop="customerName" label="预约客户" min-width="120" align="center"></el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            v-if="scope.row.status === 1"
            type="text" 
            size="small" 
            style="color: #F56C6C"
            @click="handleCancel(scope.row)"
          >
            取消
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增预约弹窗 -->
    <el-dialog
      title="新增预约"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="充电桩编号" prop="chargerId">
          <el-select 
            v-model="formData.chargerId" 
            placeholder="请选择充电桩"
            filterable
            :loading="chargerLoading"
            @change="handleChargerChange"
          >
            <el-option
              v-for="charger in chargerOptions"
              :key="charger.id"
              :label="charger.chargerNumber"
              :value="charger.id">
              <span>{{ charger.chargerNumber }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ charger.stationName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约开始时间" prop="appointmentTime">
          <el-date-picker
            v-model="formData.appointmentTime"
            type="datetime"
            placeholder="选择预约时间"
            value-format="yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now();
              }
            }"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时长" prop="duration">
          <el-input-number 
            v-model="formData.duration" 
            :min="30"
            :max="180"
            :step="15"
            controls-position="right"
          >
          </el-input-number>
          <span class="duration-tip">分钟（最短30分钟，最长180分钟）</span>
        </el-form-item>
        <el-form-item label="预约客户" prop="customerId">
          <el-select 
            v-model="formData.customerId" 
            placeholder="请选择客户"
            filterable
            :loading="customerLoading"
            @change="handleCustomerChange"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.id">
              <span>{{ item.customerName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phoneNumber }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            v-model="formData.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AppointmentManage',
  data() {
    return {
      searchQuery: '',
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedRows: [],
      loading: false,
      dialogVisible: false,
      submitLoading: false,
      chargerLoading: false,
      customerLoading: false,
      chargerOptions: [],
      customerOptions: [],
      formData: {
        chargerId: '',
        customerId: '',
        appointmentTime: '',
        duration: 30,
        remark: ''
      },
      rules: {
        chargerId: [
          { required: true, message: '请选择充电桩', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择预约客户', trigger: 'change' }
        ],
        appointmentTime: [
          { required: true, message: '请选择预约开始时间', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '请输入预约时长', trigger: 'blur' },
          { type: 'number', min: 30, max: 180, message: '预约时长必须在30-180分钟之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    getStatusText(status) {
      switch (status) {
        case 1:
          return '预约中';
        case 2:
          return '已取消';
        case 3:
          return '已完成';
        default:
          return '未知';
      }
    },
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'warning';
        case 2:
          return 'danger';
        case 3:
          return 'success';
        default:
          return 'info';
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadData();
    },
    loadData() {
      this.loading = true;
      this.$axios.get('/api/reservation/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery ? this.searchQuery.trim() : null
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data;
          this.total = response.data.total || this.tableData.length;
        } else {
          this.$message.error(response.data.msg || '获取预约列表失败');
        }
      })
      .catch(error => {
        console.error('获取预约列表失败:', error);
        this.$message.error('获取预约列表失败，请稍后重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },
    handleAdd() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
        this.loadChargerList();
        this.loadCustomerList();
      });
    },
    handleView(row) {
      // 查看功能待实现
    },
    handleEdit(row) {
      // 编辑功能待实现
    },
    handleDelete(row) {
      this.$confirm('确认删除该预约记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/reservation/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.handleSearch();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {});
    },
    handleBatchDelete() {
      if (!this.selectedRows.length) {
        return;
      }
      
      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条预约记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deletePromises = this.selectedRows.map(row => 
          this.$axios.delete(`/api/reservation/${row.id}`)
        );

        Promise.all(deletePromises)
          .then(() => {
            this.$message.success('批量删除成功');
            this.handleSearch();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后重试');
          });
      }).catch(() => {});
    },
    handleComplete(row) {
      this.$confirm('确认完成该预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        // 完成功能待实现
      }).catch(() => {});
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1;
      this.loadData();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.loadData();
    },
    // 加载充电桩列表
    loadChargerList() {
      this.chargerLoading = true;
      this.$axios.get('/api/charger/chargerList')
        .then(response => {
          if (response.data.code === 200) {
            this.chargerOptions = response.data.data;
            console.log('Charger options:', this.chargerOptions);
          } else {
            this.$message.error(response.data.msg || '获取充电桩列表失败');
          }
        })
        .catch(error => {
          console.error('获取充电桩列表失败:', error);
          this.$message.error('获取充电桩列表失败，请稍后重试');
        })
        .finally(() => {
          this.chargerLoading = false;
        });
    },
    // 加载客户列表
    loadCustomerList() {
      this.customerLoading = true;
      this.$axios.get('/api/customer/list', {
        params: {
          pageNum: 1,
          pageSize: 100  // 获取较多数据以供选择
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.customerOptions = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取客户列表失败');
        }
      })
      .catch(error => {
        console.error('获取客户列表失败:', error);
        this.$message.error('获取客户列表失败，请稍后重试');
      })
      .finally(() => {
        this.customerLoading = false;
      });
    },
    // 充电桩选择变更处理
    handleChargerChange(chargerId) {
      const selectedCharger = this.chargerOptions.find(item => item.id === chargerId);
      if (selectedCharger) {
        this.formData.chargerId = selectedCharger.id;
        this.formData.chargerNumber = selectedCharger.chargerNumber;
        console.log('Selected charger:', selectedCharger);
      }
    },
    // 客户选择变更处理
    handleCustomerChange(customerId) {
      const selectedCustomer = this.customerOptions.find(item => item.id === customerId);
      if (selectedCustomer) {
        this.formData.customerId = selectedCustomer.id;
        this.formData.customerName = selectedCustomer.customerName;
      }
    },
    // 弹窗关闭处理
    handleDialogClose() {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogVisible = false;
        this.$refs.formRef.resetFields();
      }).catch(() => {});
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 构造预约数据，使用驼峰命名
          const reservation = {
            chargerId: this.formData.chargerId,
            customerId: this.formData.customerId,
            reservationStartTime: this.formData.appointmentTime,
            reservationDuration: parseInt(this.formData.duration),
            description: this.formData.remark || ''
          };

          console.log('提交的预约数据:', reservation);

          this.$axios.post('/api/reservation/add', reservation)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('新增预约成功');
                this.dialogVisible = false;
                this.handleSearch();
              } else {
                this.$message.error(response.data.msg || '新增预约失败');
              }
            })
            .catch(error => {
              console.error('新增预约失败:', error);
              this.$message.error('新增预约失败，请稍后重试');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      });
    },
    // 取消预约
    handleCancel(row) {
      this.$confirm('确认取消该预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateData = {
          ...row,
          status: 2  // 将状态更新为已取消
        };
        
        this.$axios.post('/api/reservation/update', updateData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('预约已取消');
              this.loadData(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '取消预约失败');
            }
          })
          .catch(error => {
            console.error('取消预约失败:', error);
            this.$message.error('取消预约失败，请稍后重试');
          });
      }).catch(() => {});
    }
  },
  created() {
    this.loadData();
  }
}
</script>

<style scoped>
.appointment-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  font-size: 24px;
  margin-right: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-button--text + .el-button--text) {
  margin-left: 0;
}

:deep(.el-tag) {
  text-transform: uppercase;
}

.duration-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 180px;
}
</style>
